package com.qww.exec11;

/**
 * 当垃圾回收器找到一个有资格进行回收但有一个对象的对象时，finalizer它不会立即取消分配它。
 * 垃圾回收器试图尽快完成，因此它只是将对象添加到具有待定finalizer的对象列表中。finalizer稍后在单独的线程上调用。
 * 通过System.runFinalization在垃圾回收之后调用该方法，可以告诉系统立即尝试运行挂起的finalizer。
 * 但是，如果要强制运行finalizer，则必须自己调用它。
 * 垃圾回收器不保证将回收任何对象或将调用finalizer。这只是“尽力而为”。但是，很少需要强制finalizer以实际代码运行。
 */
public class Exec11 {

    public static void main(String[] args) {
        WebBank bank1 = new WebBank(true);
        WebBank bank2 = new WebBank(true);
        new WebBank(true);
        // Proper cleanup: log out of bank1 before going home:
        bank1.logOut();
        // Forget to logout of bank2 and unnamed new bank
        // Attempts to finalize any missed banks:
        System.out.println("Try 1: ");
        System.runFinalization();
        System.out.println("Try 2: ");
        Runtime.getRuntime().runFinalization();
        System.out.println("Try 3: ");
        System.gc();
        System.out.println("Try 4: ");
        // using deprecated since 1.1 method:
        System.runFinalizersOnExit(true);
    }
}

// initialization/BankTest.java
// TIJ4 Chapter Initialization, Exercise 11, page 177
// Modify the previous exercise so that finalize() will always be called.
class WebBank {
    boolean loggedIn = false;
    WebBank(boolean logStatus) {
        loggedIn = logStatus;
    }
    void logOut() {
        loggedIn = false;
    }
    protected void finalize() {
        if(loggedIn)
            System.out.println("Error: still logged in");
        // Normally, you'll also call the base-class version:
        // super.finalize();
    }
}

